<template>
  <div class="page-mobile-login">
    <div class="logo">
      <img @click="$router.push('/m')" :src="web_info.SUB_LOGO" alt="">
    </div>
    <div class="login-type">
      <div :class="['account',login_type == 'account'?'active':'']" @click="toggleNav('account')">账号登录</div>
      <!-- <div class="line" v-show="false">|</div>
      <div class="code" v-show="false">验证码登录</div>
      <div class="line" v-show="kl_md.KLDX == 1">|</div>
      <div :class="['parent',login_type == 'parent'?'active':'']" @click="toggleNav('parent')" v-show="kl_md.KLDX == 1">家长登录</div> -->
    </div>
    <div class="login-box">
      <div class="box-item">
        <input type="text" class="input-box" placeholder="请输入账号" v-model="param.username">
        <img class="phone-icon" src="/img/mobile/sign_phone.png" alt="">
        <div class="tips" v-show="rule.username">{{$t('locale.mobile.login.t2')}}</div>
      </div>
      <!-- <div class="box-item">
        <input type="text" class="input-box" id="password" placeholder="请输入密码" v-model="param.password">
        <img class="phone-icon" src="/img/mobile/sign_lock.png" alt="">
        <div class="tips" v-show="rule.password">{{$t('locale.mobile.login.t4')}}</div>
      </div> -->
      <div class="box-item">
        <van-field v-model="tempPwd" style="border-radius: 0.384rem;" @input="formatPassword" placeholder="请输入密码" />
        <img class="phone-icon" src="/img/mobile/sign_lock.png" alt="">
        <div class="tips" v-show="rule.password">{{$t('locale.mobile.login.t4')}}</div>
      </div>
    </div>
    
    <div class="login-box" v-if="false">
      <div class="box-item">
        <input type="text" class="input-box" placeholder="请输入账号" v-model="param.username">
        <img class="phone-icon" src="/img/mobile/sign_phone.png" alt="">
        <div class="tips" v-show="rule.username">{{$t('locale.mobile.login.t2')}}</div>
      </div>
      <div class="box-code">
        <div class="code-left">
          <input type="text" class="code" placeholder="请输入验证码" v-model="code">
        </div>
        <div class="code-right">
          <div class="get-code" v-show="false">获取验证码</div>
          <div class="set-time" v-show="true">已发送60</div>
        </div>
      </div>
    </div>
    <div class="login-btn" @click="onSubmit">登录</div>
    
    <div class="signin">
      <div><nuxt-link to="/m/edit-detail?info=password&forgetPass=1">忘记密码？</nuxt-link></div>
      <div><nuxt-link to="/m/regist">新用户注册</nuxt-link></div>
    </div>
    <div class="user-read">
      <!-- 您需要同意相关条款才能登录 -->
      <template v-if="kl_md.KLHWSC == 1">
        <van-checkbox v-model="checked"  icon-size="16px" style="margin-right:.1rem"></van-checkbox>
        我同意《<nuxt-link to="/m/protocol">用户协议</nuxt-link>》《<nuxt-link to="/m/privacy-policy">隐私保护指引</nuxt-link>》
      </template>
      <template v-else>
        登录即代表同意《<nuxt-link to="/m/protocol">用户协议</nuxt-link>》《<nuxt-link to="/m/privacy-policy">隐私保护指引</nuxt-link>》
      </template>
      
      <!-- 登录即代表同意《用户协议》《隐私保护指引》 -->
      <!-- <img src="/img/mobile/login-dui.png" alt=""> -->
      <!-- 登录即代表您已经阅读并同意《<nuxt-link to="/m/protocol">用户协议</nuxt-link>》和《<nuxt-link to="/m/privacy-policy">隐私保护指引</nuxt-link>》 -->
    </div>
    <div class="tohome" v-show="login_type != 'parent'">
      <span @click="$router.push('/m')">返回首页</span>
    </div>
    <div class="wechat" v-show="is_show_third_part_login">
      <div class="other-login">其他登录方式</div>
      <!-- <div class="onekey" @click="oneKeyLogin" v-show="kl_md.KLYJDL == 1">微信一键登录</div> -->
      <div class="wechat-login" v-show="kl_md.KLYJDL == 1 && is_in_minigram && is_wechat && third_part_login.mp">
        <img src="/img/share-icon-wechat.png" alt="" @click="oneKeyLogin">
        <div class="wechat-name">微信一键登录</div>
      </div>
      <div class="wechat-login" v-show="(kl_md.KLYJDL == 1 && !is_in_minigram) || (kl_md.KLYJDL != 1) && is_wechat && third_part_login.mp">
        <img src="/img/share-icon-wechat.png" alt="" @click="thirdPartLogin('wechat')">
        <div class="wechat-name">微信登录</div>
      </div>
    </div>
    <van-dialog
      v-model="is_show_modal"
      @cancel="is_show_modal = false"
      :title="$t('locale.mobile.login.t16')"
      @close="is_show_modal = false"
      show-cancel-button
      :show-confirm-button="false"
    >
      <verify-slider
        ref="verify_slider"
        style="width:100%;margin:0.285rem 0 0 0"
        @success="handleSuccess"
      ></verify-slider>
    </van-dialog>
    <div v-show="isShowLoginModel" class="login-container-box">
      <div id="login-container-box"></div>
    </div>
    
  </div>
</template>

<script>
import { mapMutations, mapState, mapActions } from "vuex";
import { userLogin, wxLogin,userLogout } from "~/api/account/user";
import { getMemberInfo, getMember } from "~/api/member";
import { setInClient } from "~/utils/cookies.js";
import VerifySlider from "~/components/vue-verify-slider.vue";
export default {
  components: { VerifySlider },
  data() {
    return {
      checked:false,
      isShowLoginModel:false,
      param: {
        username: "",
        password: ""
      },
      rule:{
        username:false,
        password:false,
      },
      code:"",
      rememberme: false,
      is_show_modal: false,
      login_type:"account",
      flag:false,
      tempPwd:"",
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      web_info(state) {
        return state.web_info;
      },
      third_part_login(state) {
        return state.third_part_login;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_hidden_for_ios(state) {
        return state.is_hidden_for_ios;
      },
      is_hidden_content(state) {
        return state.is_hidden_content;
      }
    }),
    is_wechat() {
      if (process.client) {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    is_minigram() {
      if (!wx.miniProgram) {
        return false;
      }
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {
          return true;
        } else {
          return false;
        }
      });
    },
    is_show_third_part_login() {
      let res = Object.keys(this.third_part_login).filter(i => {
        if (i == "mp") {
          return this.is_wechat && this.third_part_login[i] === true;
        } else if (i == "open") {
          return false;
        } else {
          return this.third_part_login[i] === true;
        }
      });
      console.log("res:", res);
      return (
        res.length > 0 && !this.is_hidden_for_ios && !this.is_hidden_content
      );
    }
  },
  watch: {},
  methods: {
    ...mapMutations([
      "SET_IS_LOADING",
      "SET_TOKEN",
      "SET_USERINFO",
      "SET_LOGINTYPE",
      "SET_MEMBER_DISCOUNT",
      "SET_MEMBER_INFO",
      "SET_USERTYPE"
    ]),
    ...mapActions(["initBuyRecord", "initBuyCourseRecord","initSignAgreement","initSignInCourse", "initRtcInfo","initAuthentication","getMineV2QuestionBankList"]),
    //微信一键登录
    oneKeyLogin(){
      wx.miniProgram.navigateTo({
        url: `/pages/login/login?ip=${returnCitySN.cip}`,
        success: function() {
          console.log("成功跳转小程序");
        },
        fail: function() {
          console.log("跳转小程序失败");
        },
        complete: function() {
          console.log("完成");
        }
      });
    },
    formatPassword(val){
      
      this.tempPwd = "";
      for (let i = 0; i < val.length; i++) {
        this.tempPwd += "●"
      }
      if(this.param.password.length < this.tempPwd.length){
        this.param = {
          ...this.param,
          password : this.param.password + val.substring(this.param.password.length, this.tempPwd.length)
        }
      }else{
        this.param = {
          ...this.param,
          password : this.param.password.substring(0, this.tempPwd.length)
        }
      }
    },
    toggleNav(type){
      this.login_type = type;
    },
    onSubmit() {
      
      const { username, password } = this.param;
      if(!username){
        this.rule.username = true;
      }else{
        this.rule.username = false;
      }
      if(!password){
        this.rule.password = true;
      }else{
        this.rule.password = false;
      }
      if (!username || !password) {
        return;
      }
      // 判断未勾选隐私协议按钮
      if(!this.checked && this.kl_md.KLHWSC == 1){
        this.$toast('您需要同意相关条款才能登录');
        return;
      }
      //登录拼图滑动验证
      // let box=document.getElementById("login-container-box");
      // box.innerHTML = "";
      // this.isShowLoginModel = true;
      // let that = this;
      // jigsaw.init({
      //   el: document.getElementById('login-container-box'),
      //   width: 310, // 可选, 默认310
      //   height: 155, // 可选, 默认155
      //   onSuccess: function () {
      //     this.isShowLoginModel = false;
      //     that.handleSuccess()
      //   },
      //   onFail: function () {},
      //   onRefresh: function () {}
      // })
      
      //正常滑动验证
      // this.is_show_modal = true;
      this.handleSuccess();
    },
    //微信一键登录
    async wxOneKeyLogin(account,password){
      let params = {
        account,
        password
      }
      let login_type = "account";
      this.SET_IS_LOADING(true);
      let result = await userLogin(params);
      if (result.data.code === 200) {
        this.SET_TOKEN(result.headers.authorization);
        this.SET_USERINFO(result.data.data, this.rememberme);
        this.SET_LOGINTYPE(login_type);
        this.SET_USERTYPE("student");
        this.$toast(this.$t("locale.mobile.login.t17"));
        this.initBuyRecord();
        this.initRtcInfo();
        this.initBuyCourseRecord();
        this.initSignAgreement();
        this.initSignInCourse();
        this.initAuthentication();

        let memberDiscount = await getMemberInfo(result.data.data.id);
        let member = await getMember(result.data.data.id);
        // console.log("memberDiscount",memberDiscount.data.data)
        this.SET_MEMBER_DISCOUNT(memberDiscount.data.data);
        this.SET_MEMBER_INFO(member.data.data);

        this.initState();
        // this.$router.replace("/m");
        wx.miniProgram.reLaunch({
          url: `/pages/index/index`,
          success: function() {
            console.log("成功跳转小程序");
          },
          fail: function() {
            console.log("跳转小程序失败");
          },
          complete: function() {
            console.log("完成");
          }
        });
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        // const { verify_slider } = this.$refs;
        // verify_slider.initComponent.call(verify_slider);
        this.$toast(
          this.$t("locale.mobile.login.t18") +
            (result && result.data && result.data.msg)
        );
      }
    },
    async handleSuccess() {
      if(!this.flag){
        this.flag = true;
      }else{
        return false;
      }
      let email_reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      let phone_reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      let login_type = "";
      let params = {
        password: this.param.password,
        rememberme: this.rememberme
      };
      if (email_reg.test(this.param.username)) {
        params = {
          ...params,
          email: this.param.username
        };
        login_type = "email";
      } else if (phone_reg.test(this.param.username)) {
        params = {
          ...params,
          account: this.param.username
        };
        login_type = "mobile";
      } else {
        params = {
          ...params,
          account: this.param.username
        };
        login_type = "account";
      }
      if(this.login_type == 'parent'){
        params = {
          ...params,
          user_type:1
        }
      }
      this.is_show_modal = false;
      this.isShowLoginModel = false;
      this.SET_IS_LOADING(true);
      let result = await userLogin(params);
      this.flag = false;
      if (result.data.code === 200) {
        this.SET_TOKEN(result.headers.authorization);
        this.SET_USERINFO(result.data.data, this.rememberme);
        this.SET_LOGINTYPE(login_type);
        if(this.login_type == 'parent'){
          this.SET_USERTYPE("parent");
        }else{
          this.SET_USERTYPE("student");
        }
        this.$toast(this.$t("locale.mobile.login.t17"));
        this.initBuyRecord();
        this.initRtcInfo();
        this.initBuyCourseRecord();
        this.initSignAgreement();
        this.initSignInCourse();
        this.initAuthentication();
        this.getMineV2QuestionBankList();

        let memberDiscount = await getMemberInfo(result.data.data.id);
        let member = await getMember(result.data.data.id);
        // console.log("memberDiscount",memberDiscount.data.data)
        this.SET_MEMBER_DISCOUNT(memberDiscount.data.data);
        this.SET_MEMBER_INFO(member.data.data);

        this.initState();
        if(this.login_type == 'parent'){
          this.$router.replace("/m/parent");
        }else{
          this.$router.replace("/m");
        }
        // this.$router.replace("/m");
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        // const { verify_slider } = this.$refs;
        // verify_slider.initComponent.call(verify_slider);
        this.$toast(
          this.$t("locale.mobile.login.t18") +
            (result && result.data && result.data.msg)
        );
      }
    },
    async thirdPartLogin(type) {
      if (type == "wechat") {
        let result = await wxLogin(1);
        console.log("result:", result);
        if (result.data.code == 200) {
          window.location.href = result.data.msg;
          // window.location.href =
          //   "weixin://dl/businessWebview/link/?appid=wx0d853b378eb4ae4e&url=" +
          //   encodeURI(result.data.msg);
        } else {
          this.$toast(this.$t("locale.mobile.login.t19"));
        }
      }
    },
    //清空登录信息
    async logout(){
      let params = {};
      if (this.login_type == "email") {
        params = {
          email: this.user_info.email
        };
      } else if (this.login_type == "mobile") {
        params = {
          account: this.user_info.mobile
        };
      } else {
        params = {
          account: this.user_info.account
        };
      }
      let result = await userLogout(params);
      if (result.data.code === 200) {
        this.$store.commit("SIGN_OUT");
        // this.$router.replace("/m/user");
        // this.$toast(this.$t("locale.mobile.user.t18"));
      } else {
        this.$store.commit("SIGN_OUT");
        // this.$toast(this.$t("locale.mobile.user.t19"));
      }
    },
    initState() {
      console.log("初始state");
      this.param = {
        username: "",
        password: ""
      };
      this.tempPwd = "";
      this.rememberme = false;
      this.is_show_modal = false;
      this.isShowLoginModel = false;
      // const { verify_slider } = this.$refs;
      // verify_slider && verify_slider.initComponent.call(verify_slider);
    }
  },
  created() {
    if (process.client) {
      if (this.token && Object.keys(this.user_info).length > 0) {
        // this.$router.replace("/m");
        //解决微信登录问题
        this.logout();
      }else{
        let {account,password} = this.$route.query
        console.log(account,password);
        if(account && password){
          this.wxOneKeyLogin(account,password)
        }
        
      }
    }
  },
  activated() {
    if (process.client) {
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.$router.replace("/m");
      }
    }
  },
  deactivated() {
    this.initState();
  },
  mounted() {}
};
</script>
<style lang="scss">
.page-mobile-login{
  .van-cell{
    padding: 0;
    .van-field__control{
      width: 100%;
      box-sizing: border-box;
      padding-left: 1rem;
      height: .768rem;
      border-radius: 0.384rem;
      border: none;
      line-height: .768rem;
      font-size: .3rem;
    }
    input::-webkit-input-placeholder { 
      /* WebKit browsers */ 
      color: rgb(81, 90, 110); 
    } 
    input:-moz-placeholder { 
      /* Mozilla Firefox 4 to 18 */ 
      color: rgb(81, 90, 110); 
    } 
    input::-moz-placeholder { 
      /* Mozilla Firefox 19+ */ 
      color: rgb(81, 90, 110); 
    } 
    input:-ms-input-placeholder { 
      /* Internet Explorer 10+ */ 
      color: rgb(81, 90, 110); 
    }
  }
}

</style>
<style lang="scss" scoped>
.page-mobile-login {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 1rem;
  .login-container-box{
    position: fixed;
    // width: 5.952rem;
    // height: 2.976rem;
    width: 7.2rem;
    height: 100%;
    z-index: 2001;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
  .logo{
    width: 1.536rem;
    height: 1.536rem;
    margin: 0rem auto;
    img{
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .login-type{
    width: 5.568rem;
    margin: .6rem auto;
    display: flex;
    justify-content: center;
    font-size: .3264rem;
    font-weight: bold;
    .account{
      width: 2rem;
      text-align: center;
      color: #adafb2;
    }
    .account.active{
      color: var(--theme-color);
    }
    .line{
      margin: 0 .2rem;
      color: #dadce0;
    }
    .code{
      width: 2rem;
      text-align: center;
      color: #adafb2;
    }
    .code.active{
      color: var(--theme-color);
    }
    .parent{
      width: 2rem;
      text-align: center;
      color: #adafb2;
    }
    .parent.active{
      color: var(--theme-color);
    }
  }
  .login-box{
    width: 5.568rem;
    margin: .3rem auto;
    .box-item{
      width: 100%;
      height: .768rem;
      border-radius: 0.384rem;
      margin-bottom: .5rem;
      background: #ffffff;
      position: relative;
      &::after{
        content: "";
        display: block;
        position: absolute;
        left: .9rem;
        top: 50%;
        z-index: 9;
        transform: translateY(-50%);
        height: .3168rem;
        width: .03rem;
        background-color: #c6c8cc;
      }
      .tips{
        position: absolute;
        left: 1rem;
        bottom: -.4rem;
        color: red;
        font-size: .22rem;
      }
      .phone-icon{
        position: absolute;
        left: .4rem;
        top: 50%;
        transform: translateY(-50%);
        height: .3168rem;
        width: .27456rem;
        display: block;
      }
      .input-box{
        width: 100%;
        box-sizing: border-box;
        padding-left: 1rem;
        height: .768rem;
        border-radius: 0.384rem;
        border: none;
        line-height: .768rem;
        font-size: .3rem;
      }
      #password{
        -webkit-text-security: disc;
      }
    }
    .box-code{
      margin-bottom: .5rem;
      display: flex;
      justify-content: space-between;
      .code-left{
        width: 56%;
        height: .768rem;
        border-radius: 0.384rem;
        background: #ffffff;
        .code{
          width: 100%;
          box-sizing: border-box;
          padding: 0 .3rem;
          height: .768rem;
          border-radius: 0.384rem;
          border: none;
          line-height: .768rem;
          font-size: .3rem;
        }
      }
      .code-right{
        width: 40%;
        .get-code{
          width: 100%;
          box-sizing: border-box;
          padding: 0 .3rem;
          height: .768rem;
          text-align: center;
          border-radius: 0.384rem;
          line-height: .768rem;
          font-size: .3rem;
          background: var(--theme-color);
          color: #ffffff;
        }
        .set-time{
          width: 100%;
          box-sizing: border-box;
          padding: 0 .3rem;
          height: .768rem;
          text-align: center;
          border-radius: 0.384rem;
          border: none;
          line-height: .768rem;
          font-size: .3rem;
          background:#dadce0;
        }
      }

    }
  }
  .login-btn{
    width: 5.568rem;
    margin: .7rem auto .3rem;
    height: .768rem;
    line-height: .768rem;
    border-radius: 0.384rem;
    text-align: center;
    font-size: .3rem;
    font-weight: bold;
    background: var(--theme-color);
    color: #ffffff;
  }
  .user-read{
    font-size: .24rem;
    width: 5.568rem;
    margin: 0rem auto;
    display: flex;
    align-items: center;
    img{
      display: block;
      width: .2496rem;
      height: .2496rem;
      margin-right: .1rem;
    }
    a{
      color: var(--theme-color);
    }
  }
  .tohome{
    width: 5.568rem;
    margin: .2rem auto 0;
    text-align: right;
    font-size: .2496rem;
    font-weight: bold;
    color: #949699;
  }
  .signin{
    font-size: .24rem;
    width: 5.568rem;
    margin: .2rem auto;
    display: flex;
    justify-content: space-between;
    a{
      color: var(--theme-color);
    }
  }
  .wechat{
    font-size: .3rem;
    width: 5.568rem;
    margin: 0 auto;
    padding: .3rem 0;
    .other-login{
      width: 2rem;
      margin: 0 auto;
      text-align: center;
      margin-bottom: .5rem;
      position: relative;
      &::before{
        content: "";
        display: block;
        width: 1.5rem;
        height: .03rem;
        background: #dadce0;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translate(-110%,-50%);
      }
      &::after{
        content: "";
        display: block;
        width: 1.5rem;
        height: .03rem;
        background: #dadce0;
        position: absolute;
        right: 0;
        top: 50%;
        transform: translate(110%,-50%);
      }
    }
    .wechat-login{
      text-align: center;
      img{
        width: .8rem;
        height: .8rem;
        margin: 0 auto;
        display: block;
      }
      .wechat-name{
        margin-top: .1rem;
      }
    }
  }
  .van-dialog {
    .drag {
      height: 0.75rem;
      line-height: 0.71rem;
      .drag_bg {
        height: 0.75rem;
      }
      .drag_text {
        height: 0.75rem;
        font-size: 0.24rem;
      }
      .handler {
        width: 0.75rem;
        height: 0.75rem;
      }
    }
  }
}
</style>

